// 全局变量
let order = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    checkLoginStatus();
    loadOrderDetails();
});

// 检查登录状态
function checkLoginStatus() {
    const token = localStorage.getItem('token');
    if (!token) {
        alert('请先登录');
        window.location.href = '/login.html';
        return;
    }
}

// 加载订单详情
async function loadOrderDetails() {
    const urlParams = new URLSearchParams(window.location.search);
    const orderId = urlParams.get('id');

    if (!orderId) {
        alert('订单ID无效');
        window.location.href = '/index.html';
        return;
    }

    try {
        const response = await fetch(`/api/orders/${orderId}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (!response.ok) {
            throw new Error('加载订单失败');
        }

        order = await response.json();
        displayOrderDetails();
    } catch (error) {
        console.error('加载订单失败:', error);
        alert('加载订单失败');
    }
}

// 显示订单详情
function displayOrderDetails() {
    if (!order) return;

    // 显示订单基本信息
    document.getElementById('orderId').textContent = order.id;
    document.getElementById('orderStatus').textContent = getStatusText(order.status);
    document.getElementById('orderDate').textContent = new Date(order.created_at).toLocaleString();
    document.getElementById('totalAmount').textContent = `¥${order.total_amount.toFixed(2)}`;

    // 显示订单商品
    const orderItemsList = document.getElementById('orderItemsList');
    orderItemsList.innerHTML = '';

    order.items.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <img src="${item.product.image_url || 'images/default-product.jpg'}" 
                     class="order-item-image" alt="${item.product.name}">
            </td>
            <td>${item.product.name}</td>
            <td>¥${item.product.price}</td>
            <td>${item.quantity}</td>
            <td>¥${(item.product.price * item.quantity).toFixed(2)}</td>
        `;
        orderItemsList.appendChild(row);
    });

    // 显示收货地址
    document.getElementById('shippingAddress').textContent = order.shipping_address;

    // 根据订单状态显示操作按钮
    const orderActions = document.getElementById('orderActions');
    orderActions.innerHTML = '';

    if (order.status === 'pending') {
        const cancelButton = document.createElement('button');
        cancelButton.className = 'btn btn-danger';
        cancelButton.textContent = '取消订单';
        cancelButton.onclick = () => cancelOrder(order.id);
        orderActions.appendChild(cancelButton);

        const payButton = document.createElement('button');
        payButton.className = 'btn btn-primary ms-2';
        payButton.textContent = '立即支付';
        payButton.onclick = () => payOrder(order.id);
        orderActions.appendChild(payButton);
    }
}

// 获取订单状态文本
function getStatusText(status) {
    const statusMap = {
        'pending': '待支付',
        'paid': '已支付',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 取消订单
async function cancelOrder(orderId) {
    if (!confirm('确定要取消订单吗？')) {
        return;
    }

    try {
        const response = await fetch(`/api/orders/${orderId}/cancel`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (!response.ok) {
            throw new Error('取消订单失败');
        }

        alert('订单已取消');
        loadOrderDetails();
    } catch (error) {
        console.error('取消订单失败:', error);
        alert('取消订单失败');
    }
}

// 支付订单
async function payOrder(orderId) {
    try {
        const response = await fetch(`/api/orders/${orderId}/pay`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (!response.ok) {
            throw new Error('支付失败');
        }

        alert('支付成功');
        loadOrderDetails();
    } catch (error) {
        console.error('支付失败:', error);
        alert('支付失败');
    }
} 